#include "widget.h"
#include "ui_widget.h"
#include "insertdialog.h"

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QString>
#include <QSqlError>
#include <QSqlQueryModel>
#include <QDate>

#include <QMessageBox>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
//    this->setWindowTitle("计工");
    qApp->setStyleSheet("QWidget{font-size: 16px; border-radius: 5%;}");
    ui->tableView->setStyleSheet("QTableView::item:selected{\
                                 color:red;\
                                 background:rgb(34, 175, 75); \
                         }");

    m_model = new QSqlQueryModel(this);
    ui->tableView->setModel(m_model);
    //设置自适应列宽
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    //设置整行选中
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    //打开数据库
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("zuogong");
    if(!db.open())
    {
        QMessageBox::critical(0, "严重错误!", "数据库(QSQLITE)打开失败!");
        exit(1);
    }
    //查看数据库是否存在，不存在就创建
    QSqlQuery query;
    query.exec("SELECT * FROM sqlite_master WHERE NAME = 'zuogong'");
    if(!query.next())
    {
        QString queryString("CREATE TABLE zuogong (\
                            id INTEGER PRIMARY KEY AUTOINCREMENT,\
                            recordDate DATE NOT NULL,\
                            gongCount FLOAT NOT NULL,\
                            remarks CHAR(255))");
        if(!query.exec(queryString))
        {
            QSqlError error = query.lastError();
            QMessageBox::critical(0, "严重错误!", QString("%1\n%2\n%3")
                                  .arg(error.databaseText())
                                  .arg(error.driverText())
                                  .arg("数据库创建失败!"));
            exit(1);
        }
    }
    //显示全部数据
    ui->dateEditBegin->setDate(QDate(2010, 1, 1));
    ui->dateEditEnd->setDate(QDate::currentDate());
    this->showAll();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_btnSelect_clicked()
{
    this->showAll();
}

void Widget::on_btnDelete_clicked()
{
    int row = ui->tableView->currentIndex().row();
    int id = m_model->itemData(m_model->index(row, 0))[0].toInt();
    //删除选中数据
    m_model->setQuery(QString("DELETE FROM zuogong WHERE id == %1").arg(id));

    this->showAll();
}

void Widget::showAll()
{
    m_model->setQuery(QString("SELECT id, recordDate, gongCount, remarks\
                      FROM zuogong\
                      WHERE recordDate BETWEEN '%1' AND '%2'\
                      ORDER BY recordDate DESC")
                      .arg(ui->dateEditBegin->date().toString("yyyy-MM-dd"))
                      .arg(ui->dateEditEnd->date().toString("yyyy-MM-dd")));
    //设置表头(列名)
    m_model->setHeaderData(0, Qt::Horizontal, "ID");
    m_model->setHeaderData(1, Qt::Horizontal, "日期");
    m_model->setHeaderData(2, Qt::Horizontal, "计工");
    m_model->setHeaderData(3, Qt::Horizontal, "备注");
    //显示两个日期之间的数据
    ui->tableView->show();
    //隐藏第0列
    ui->tableView->hideColumn(0);

    QSqlQuery query = m_model->query();
    //统计数据
    query.exec(QString("SELECT COUNT(recordDate), SUM(gongCount)\
                       FROM zuogong\
                       WHERE recordDate BETWEEN '%1' AND '%2'")
                       .arg(ui->dateEditBegin->date().toString("yyyy-MM-dd"))
                       .arg(ui->dateEditEnd->date().toString("yyyy-MM-dd")));
    if(query.next()){
        ui->lineEditSelectResult->setText(QString("一共: %1 天, %2 个工")
                                          .arg(query.value(0).toInt())
                                          .arg(query.value(1).toFloat()));
    }
    else{
        ui->lineEditSelectResult->setText("没有查询到数据！");
    }
}

void Widget::on_btnAdd_clicked()
{
    QString value;
    InsertDialog *dialog = new InsertDialog(&value, this);
    //以模态模式显示
    dialog->exec();
    //
    if(!value.isEmpty())
    {
        this->m_model->setQuery(QString("INSERT INTO zuogong (recordDate, gongCount, remarks) VALUES(%1)").arg(value));
        this->showAll();
    }

//    dialog->show();
//    qDebug() << "value = " << value;
//    connect(dialog, &InsertDialog::insertValue, [this](const QString &value)
//    {
//        qDebug() << "value = " << value;

//        this->m_model->setQuery(QString("INSERT INTO zuogong (recordDate, gongCount, remarks) VALUES(%1)").arg(value));

//        this->showAll();
//    });
}

void Widget::on_tableView_clicked(const QModelIndex &index)
{
    int row = index.row();
    QString str = m_model->itemData(m_model->index(row, 3))[0].toString();
//    QString str = m_model->itemData(index)[0].toString();
    ui->editDetails->clear();
    ui->editDetails->setText(str);
}
